package com.mynetwork.data;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.util.zip.GZIPOutputStream;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.mynetwork.utils.FileUtils;
import com.mynetwork.utils.SystemInfoUtils;
import com.mynetwork.utils.Utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.util.Log;

public class StatisticsManager {
	private static final String TAG = "StatisticsUtils";
	
	public static StatisticsManager mInstance = null;
	public static StatisticsManager getInstance() {
		if (mInstance == null) {
			mInstance = new StatisticsManager();
		}
		return mInstance;
	}
	private StatisticsManager() {}
	
	public static void SaveLog(JSONObject log) {
		try {
			FileWriter fw = new FileWriter(AppData.STATISTICS_FILE_PATH, true);
			BufferedWriter bw = new BufferedWriter(fw);
			fw.write(log.toString());
			bw.newLine();
			bw.close();
			fw.close();
		} catch (Exception e) {
			Log.e(TAG, "" + e);
		}
	}
	
	public static String getStatisticsLog() {
		try {
			File file = new File(AppData.STATISTICS_FILE_PATH);
			if (!file.exists())
				return null;
			BufferedReader in = new BufferedReader(new FileReader(AppData.STATISTICS_FILE_PATH));
			String s;
			StringBuilder builder = new StringBuilder();
			builder.append("[");
			boolean isFirst = true;
			while ((s = in.readLine()) != null) {
				if (isFirst) {
					isFirst = false;
					builder.append(s);
				} else
					builder.append("," + s);
			}
			builder.append("]");
			Log.e(TAG,"KDS3393_Log = " + builder.toString());
			in.close();
			return builder.toString();
		} catch (Exception e) {
			Log.e(TAG, "" + e);
		}
		return null;
	}
	
//	  {"cmd":"appLifeCycle","type":"start","actionTime":"20130425173000"}
//	  {"cmd":"appLifeCycle","type":"start","actionTime":"20130425173000","viewId":"none"}
	public static void setStartApp() throws JSONException {
		JSONObject array = new JSONObject();
		array.put("cmd", "appLifeCycle");
		array.put("type", "start");
		array.put("viewId", "introView");
		array.put("actionTime", Utils.getTodayDateFormat("yyyyMMddHHmmss"));
		SaveLog(array);
	}
	
//, {"cmd":"downCont","type":"start","contIdx":1,"fileIdx":3,"networkType":"3g","actionTime":"20130425173000"}
	public static void setContentStart(Context context, int contentIdx,int fileIdx) throws JSONException {
		JSONObject array = new JSONObject();
		array.put("cmd", "downCont");
		array.put("type", "start");
		array.put("contIdx", contentIdx);
		array.put("fileIdx", fileIdx);
		int type = SystemInfoUtils.getConnectedNetwork(context);
		if (type == ConnectivityManager.TYPE_WIFI) {
			array.put("networkType", "wifi");
		} else if (type == ConnectivityManager.TYPE_MOBILE) {
			array.put("networkType", "3g");
		}
		array.put("actionTime", Utils.getTodayDateFormat("yyyyMMddHHmmss"));
		SaveLog(array);
	}
	
//	  , {"cmd":"confirmPush","pushIdx":"12","actionTime":"20130425173000"}
//	  , {"cmd":"confirmPush","pushIdx":"12","actionTime":"20130425173000"}
	public static void setConfirmPush(int pushIndex) throws JSONException {
		JSONObject array = new JSONObject();
		array.put("cmd", "confirmPush");
		array.put("pushIdx", pushIndex);
		array.put("actionTime", Utils.getTodayDateFormat("yyyyMMddHHmmss"));
		SaveLog(array);
	}

//	  , {"cmd":"confirmNotice","noticeIdx":"18","actionTime":"20130425173000"} 긴급공지 확인
//	  , {"cmd":"confirmNotice","noticeIdx":"18","actionTime":"20130425173000"}
	
	public static void setConfirmNotice(int notiIndex) throws JSONException {
		JSONObject array = new JSONObject();
		array.put("cmd", "confirmNotice");
		array.put("noticeIdx", notiIndex);
		array.put("actionTime", Utils.getTodayDateFormat("yyyyMMddHHmmss"));
		SaveLog(array);
	}

//	  , {"cmd":"appUpdate","type":"popup","actionTime":"20130425173000"} 앱 업데이트 시도
	public static void setAppUpdate(int notiIndex) throws JSONException {
		JSONObject array = new JSONObject();
		array.put("cmd", "appUpdate");
		array.put("type", "popup");
		array.put("actionTime", Utils.getTodayDateFormat("yyyyMMddHHmmss"));
		SaveLog(array);
	}
	
//	  , {"cmd":"setupPush","type":"on","actionTime":"20130425173000"} 알림 설정
//	  , {"cmd":"setupPush","type":"on","actionTime":"20130425173000"}
	public static void setSetupPush(boolean isOn) throws JSONException {
		JSONObject array = new JSONObject();
		array.put("cmd", "setupPush");
		array.put("type", isOn?"on":"off");
		array.put("actionTime", Utils.getTodayDateFormat("yyyyMMddHHmmss"));
		SaveLog(array);
	}

//	  , {"cmd":"adClick","adIdx":1,"type":"M","actionTime":"20130425173000"}
	public static void setADClickPush(int adIdx) throws JSONException {
		JSONObject array = new JSONObject();
		array.put("cmd", "adClick");
		array.put("adIdx", adIdx);
		array.put("type", "app");
		array.put("actionTime", Utils.getTodayDateFormat("yyyyMMddHHmmss"));
		SaveLog(array);
	}
	
//	  , {"cmd":"error","errorCode":"101","errorMsg":"exception","viewId":"메인화면","actionTime":"20130425173000"}
//	  , {"cmd":"detailedEvent","eventIdx":11,"actionTime":"20130425173000"}
//	  , {"cmd":"viewCont","contIdx":1,"fileIdx":2,"actionTime":"20130425173000"}
//	  , {"cmd":"viewLog","contIdx":1,"fileIdx":2,"actionTime":"20130425173000","logData":[{"PageIndex":"1", "ViewCount":"1", "ViewDuration":"20136548","ScrapCount":"0","EmailCount":"0","TwitterCount":"1","FacebookCount":"1"}, {"PageIndex":"1", "ViewCount":"1", "ViewDuration":"20136548","ScrapCount":"0","EmailCount":"0","TwitterCount":"1","FacebookCount":"1"}]}]

	//[[ Network ------------------------------------------------------------------------
	
	public OnNetworkListener mOnNetworkListener;
	public void upLoad(Context context,String data, OnNetworkListener l) {
		if (data == null) {
			l.onError(null);
			return;
		}
		mOnNetworkListener = l;
		new UpLoadAsyncTask(data).execute();

	}
	
	private class UpLoadAsyncTask extends AsyncTask<Object, Object, Boolean> {
		private String mData;
		public UpLoadAsyncTask(String data) {
			mData = data;
		}
		
		@Override
		protected Boolean doInBackground(Object... params) {
			HttpURLConnection conn = null;
			try {
				conn = NetworkManager.getUrlConnection(NetworkManager.getApiServerURL() + NetworkManager.STATISTICS_UPLOAD);
				StringBuilder strBuilder = NetworkManager.getNetworkDefaultPacket();
				
				
				Log.e(TAG,"KDS3393_orderlist_json = " + mData);
				strBuilder.append("&data=" + mData);
				
				Log.e(TAG,"KDS3393_url_logUpload = " + NetworkManager.getApiServerURL() + NetworkManager.STATISTICS_UPLOAD + strBuilder.toString());
				OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); 
	            PrintWriter writer = new PrintWriter(outStream); 
	            writer.write(strBuilder.toString()); 
	            writer.flush(); 
	            writer.close();
	            
	            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); 
	            StringBuilder builder = new StringBuilder(); 
	            String str; 
	            while ((str = reader.readLine()) != null) {       // 서버에서 라인단위로 보내줄 것이므로 라인단위로 읽는다 
	                builder.append(str + "\n");                     // View에 표시하기 위해 라인 구분자 추가 
	            } 
	            Log.e(TAG,"KDS3393_stat = " + builder.toString());
	            reader.close();
	            
				JSONObject jsonObj = new JSONObject(builder.toString());
				
				if (jsonObj.getInt("returnCode") != 0)
					return false;
			} catch (SocketTimeoutException e) {
 				Log.e(TAG,"Error : SocketTimeoutException");
 				return false;
 			} catch (ConnectTimeoutException e) {
 				Log.e(TAG,"Error : ConnectTimeoutException");
 				return false;
 			} catch (Exception e) {
 				Log.e(TAG,"" + e);
				if(conn != null){
					conn.disconnect();
					conn = null;
				}
				return false;
			}
 			return true;
 		}
 		
 		@Override
 		protected void onPostExecute(Boolean result) {
 			if (mOnNetworkListener != null) {
 				if (result) {
 					FileUtils.deleteFile(AppData.STATISTICS_FILE_PATH);
 					try {
						setStartApp();
					} catch (JSONException e) {
						Log.e(TAG,"" + e);
					}
 					mOnNetworkListener.onSuccess(null);
 				} else {
	 				try {
	 					setStartApp();
	 				} catch (JSONException e) {
	 					Log.e(TAG,"" + e);
					}
 					mOnNetworkListener.onError(null);
 				}
 			}
 		}
    }
}
